// mircoApp/ai-create/SpaceDetails/index.js
let app = getApp();
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');

Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    business_id: 0,
    activePopover: null,

    showoverlay: true,
    resetNewName: null,
    active: 0,
    list: [],

    showDigital: false,
    showDialog: false,
    showDialogUnReferImg: false,
    bodyReferImg: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: 'A' + 'I创作'
    });
    this.setData({
      business_id: Number(options.business_id) || 0
    })
    if(options.tab){
      this.setData({
        active: Number(options.tab) || 0
      })
    }    
  },
  onClickVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });
  },
  toUrl(e) {
    if (e.currentTarget.dataset.beforeread && !e.currentTarget.dataset.beforereadval) {
      wx.showModal({
        showCancel: false,
        content: '当前暂无创作次数，需购买相关权益',
      })
      return;
    }
    let _data = e.currentTarget.dataset || {};
    this.wxRouterLink(_data);
  },
  wxRouterLink(_data) {
    let _Param = "";
    const {
      url,
      ...otherParam
    } = _data;
    Object.keys(otherParam).forEach(function (key) {
      if (otherParam[key] !== "") _Param += key + "=" + otherParam[key] + "&";
    });
    if (url === "") return;
    wx.navigateTo({
      url: url + "?" + _Param.slice(0, -1),
    });
  },
  async getData() {
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.center.manage');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.init();
    this.setData(data);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.themeBaseColor
    });
  },

  init() {
    this.tabArrOption = [{
        name: "作品",
        url: 'plugin.ai-create.frontend.controllers.video.index',
        page: 1,
        finished: false,
        listName: 'videoList'
      },
      {
        name: "数字分身",
        url: 'plugin.ai-create.frontend.controllers.body.index',
        page: 1,
        finished: false,
        listName: 'bodyList'
      },
      {
        name: "声音克隆",
        url: 'plugin.ai-create.frontend.controllers.audio.index',
        page: 1,
        finished: false,
        listName: 'audioList'
      }
    ];
    this.data.videoList = [];
    this.data.bodyList = [];
    this.data.audioList = [];
    if( this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
    this.getTabsList({refresh: true});
  },
  async getTabsList({refresh = false} = {}) {
    let index = this.data.active;
    let activeTabInfo = this.tabArrOption[index];
    // if(refresh) this.data[activeTabInfo.listName] = []; //重置列表对应的data数据
    if(activeTabInfo.finished) return;//没有更多
    let urlStr = app.getNetAddresss(activeTabInfo.url);
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0,
        page: activeTabInfo.page
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    // // 添加轮询请求数据
    if(!this.data.timer) {
      this.data.timer = setInterval(() => {
        // this.init();
        let newArrStatus =  this.data[this.tabArrOption[this.data.active]["listName"]].filter(item => (item.lip && item.lip.status == 0) || (item.status == 0))
        this.getStatus(newArrStatus)
      }, 10000);
    }

    let _list = this.data[activeTabInfo.listName] || [];
    this.setData({
      [activeTabInfo.listName]:  _list.concat(data.data)
    });

    if(data.current_page == data.last_page) {
      return this.tabArrOption[index].finished = true;
    }
    this.tabArrOption[index].page += 1;
  },
  // 查询视频状态
  async getStatus(newArrStatus) {
    let urlStr = app.getNetAddresss("plugin.ai-create.frontend.controllers.video.index.get-status");
    let response = await app._postNetWork({
      url: urlStr,
      data: {ids: newArrStatus.map(item => item.id)}
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    // data = [{
    //     "id": 161,
    //     "name": "dd-唇形匹配-1740468771",
    //     "cover_img": "",
    //     "status": 1,
    //     "url": null,
    //     "path": null,
    //     "duration": 2,
    //     "has_operate": true,
    //     "has_lip_match": true,
    //     "has_delete": false,
    //     "body": {
    //         "name": "dd",
    //         "id": 41,
    //         "refer_img": "https://ysm-1251768088.cos.ap-guangzhou.myqcloud.com/images/25/2025/02/93149a98599f7ee7f0f71e02a7eac8c9.jpg",
    //         "url": "https://ysm-1251768088.cos.ap-guangzhou.myqcloud.com/ai-create/interests/25/member-164183/2025/02/d9b5cf816521393488544176d79c1f72.mp4"
    //     },
    //     "origin_video_url": "https://ysm-1251768088.cos.ap-guangzhou.myqcloud.com/ai-create/interests/25/member-164183/2025/02/397a08e5fe7527e1fcb04d41dfe1dd60.mp4",
    //     "is_lip_video": true,
    //     "lip": {
    //         "id": 56,
    //         "video_id": 161,
    //         "status": 1,
    //         "status_name": "匹配成功"
    //     },
    //     "member": null
    // }]
    const newArrVideoList = this.replaceObjectsById(data,this.data[this.tabArrOption[this.data.active]["listName"]])
    // let filed = this.tabArrOption + '[' + this.data.active + ']' + '[' + 'listName' + ']';
    let filed = this.tabArrOption[this.data.active]['listName'];
    console.log(filed,'filedfiled')
    this.setData({
      [filed]: newArrVideoList
    })
    console.log(result,
      msg,
      data,555555,this.data[this.tabArrOption[this.data.active]["listName"]],newArrVideoList)
  },
  replaceObjectsById(sourceArray, targetArray) {
      // 遍历源数组中的每个对象
      sourceArray.forEach(sourceObj => {
          // 在目标数组中查找具有相同 id 的对象的索引
          const index = targetArray.findIndex(targetObj => targetObj.id === sourceObj.id);
          // 如果找到匹配的 id
          if (index!== -1) {
              // 用源数组中的对象替换目标数组中对应的对象
              targetArray[index] = sourceObj;
          }
      });
      return targetArray;
  },
  onChangeTab(e) {
    this.setData({
      active: e.detail.name,
      activePopover: null,
    });
    // let activeTabInfo =  this.tabArrOption[e.detail.name];
    // let _data = this.data[activeTabInfo.listName] || [];
    // if(!_data.length) this.getTabsList();
    this.init();
  },
  onClickResetName(e) {
    let {
      id,
      index,
      listtype
    } = e.currentTarget.dataset;
    let _apiObj = {
      'video': {
        'api': 'plugin.ai-create.frontend.controllers.video.index.rename',
        'list': 'videoList',
        'text': '作品'
      },
      'body': {
        'api': 'plugin.ai-create.frontend.controllers.body.index.rename',
        'list': 'bodyList',
        'text': '数字分身'
      },
      'audio': {
        'api': 'plugin.ai-create.frontend.controllers.audio.index.rename',
        'list': 'audioList',
        'text': '声音'
      },
    };
    let _ResetNameInfo = _apiObj[listtype];
    _ResetNameInfo.id = id;
    _ResetNameInfo.index = index;
    this.setData({
      activePopover: null,
      ResetNameInfo: _ResetNameInfo,
      showResetName: true
    })
  },
  async submitResetName() {
    if (!this.data.resetNewName) {
      app.tips('请填写新的名称');
      return;
    }
    let urlStr = app.getNetAddresss(this.data.ResetNameInfo.api);
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0,
        name: this.data.resetNewName,
        id: this.data.ResetNameInfo.id
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.setData({
      [this.data.ResetNameInfo.list + '[' + this.data.ResetNameInfo.index + '].name']: this.data.resetNewName,
      showResetName: false,
      resetNewName: null
    })
  },
  onClickDelete(e) {
    let {
      id,
      index,
      listtype
    } = e.currentTarget.dataset;
    let _apiObj = {
      'video': {
        'api': 'plugin.ai-create.frontend.controllers.video.index.delete',
        'list': 'videoList',
        'text': '作品'
      },
      'body': {
        'api': 'plugin.ai-create.frontend.controllers.body.index.delete',
        'list': 'bodyList',
        'text': '分身'
      },
      'audio': {
        'api': 'plugin.ai-create.frontend.controllers.audio.index.delete',
        'list': 'audioList',
        'text': '声音'
      },
    };
    this.delInfo = _apiObj[listtype];
    this.delInfo.id = id;
    this.delInfo.index = index;
    this.setData({
      activePopover: null
    });
    wx.showModal({
      title: '提示',
      content: '确定删除该' + this.delInfo.text,
      success: (res) => {
        if (res.confirm) {
          this.submitDelList();
        }
      }
    })
  },
  async submitDelList() {
    let urlStr = app.getNetAddresss(this.delInfo.api);
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0,
        id: this.delInfo.id
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    if (!result) return app.tips(msg);
    this.setData({
      [this.delInfo.list + '[' + this.delInfo.index + '].hidden']: true
    })
  },
  onPreviewVideo(e) {
    let {
      url
    } = e.currentTarget.dataset;
    wx.previewMedia({
      sources: [{
        url: url,
        type: 'video'
      }],
      current: 0,
      fail() {
        wx.showToast({
          title: '预览视频失败',
          icon: 'none'
        });
      },
    });
  },
  toReleaseVideo(e){
    let {
      item
    } = e.currentTarget.dataset;
    let videoInfo = {
      videoUrl: item.url,
      videoCover: item.cover_img
    };
    wx.setStorage({
      key: "shareVideoPath",
      data: JSON.stringify(videoInfo),
      success:()=> {
        wx.navigateTo({
          url: '/packageC/video_goods/releaseVideo/releaseVideo'
        })
      }
    })
  },
  beforeSaveVideo(e){
    let {
      url
    } = e.currentTarget.dataset;
    wx.downloadFile({
      url: url,
      success :(res)=> {
        this.saveVideo(res.tempFilePath)
      }
    })
  },
  saveVideo(src){
    wx.showLoading({
      title: '保存中',
    })
    wx.saveVideoToPhotosAlbum({
      filePath: src,
      success:(res)=>{
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
        });
      },
      fail:(err)=>{
        wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: err.errMsg,
        });
        if (err.errMsg === "saveVideoToPhotosAlbum:fail auth deny") {
          wx.openSetting({
            success(settingdata) {
              console.log(settingdata);
              if (settingdata.authSetting['scope.saveVideoToPhotosAlbum']) {
                console.log('获取权限成功，给出再次点击视频保存到相册的提示。');
              } else {
                console.log('获取权限失败，给出不给权限就无法正常使用的提示');
              }
            }
          });
        }
      }
    })
  },

  onClickLip(e={}){
    let {
      duration, body, vid
    } = e.currentTarget.dataset;
    if(!this.data.lip_duration_unused) {
      wx.showModal({
        title: '提示',
        content: '您的唇形匹配权益不足，无法进行匹配，请先进行充值！',
        confirmText: '去充值',
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/packageC/member/searchAll/searchAll?plugin_id=198'
            });
          }
        }
      });
      return;
    }
    this.setData({
      lip_duration_unused_item: duration,
      lip_duration_unused_body: body,
      lip_duration_unused_video_id: vid,
      showDialog: true
    })
  },
  onEditorReferImg(e){
    let {
      body
    } = e.currentTarget.dataset;
      this.data.bodyReferImg = body.refer_img?[{
        url: body.refer_img
      }]:[];
      this.data.refer_img = body.refer_img;
    this.setData({
      lip_duration_unused_body: body,
      bodyReferImg: this.data.bodyReferImg,
      showDigital: true
    })
  },
  onconfirmLip(){
    if(!this.data.lip_duration_unused_body.refer_img) {
      // 分身的正脸参考图为空
      this.setData({
        showDialogUnReferImg: true
      });
      return;
    }
    this.submitLip();
  },
  toUploadReferImg(){
    this.setData
  },

  // 前置校验方法
  async beforeReadReferImg (event) {
    const { file, callback } = event.detail;
    // 文件大小校验
    if (file.size > 10 * 1024 * 1024) {
      wx.showToast({ title: '文件不能超过10MB', icon: 'none' })
      return false
    }

    // 文件类型校验
    const validExt = ['jpeg', 'jpg', 'png', 'bmp', 'webp']
    const ext = file.url.split('.').pop().toLowerCase()
    if (!validExt.includes(ext)) {
      wx.showToast({ title: '仅支持图片格式：JPEG/JPG/PNG/BMP/WEBP', icon: 'none' })
      return false
    }

    // 图片尺寸校验
    try {
      const imageInfo = await this.getImageInfo(file.tempFilePath)
      const maxSide = Math.max(imageInfo.width, imageInfo.height)
      const ratio = Math.max(
        imageInfo.width / imageInfo.height,
        imageInfo.height / imageInfo.width
      )

      if (maxSide > 4096) {
        wx.showToast({ title: '图片最大边长不能超过4096px', icon: 'none' })
        return false
      }

      if (ratio > 2) {
        wx.showToast({ title: '图片长宽比不能超过2:1', icon: 'none' })
        return false
      }
      callback(true);
      return true
    } catch (error) {
      wx.showToast({ title: '图片信息获取失败', icon: 'none' })
      return false
    }
  },

  // 获取图片信息（Promise封装）
  getImageInfo(path) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: path,
        success: resolve,
        fail: reject
      })
    })
  },

  // 上传文件
  uploadImageReferImg(event) {
    const { file } = event.detail
    this.setData({
      bodyReferImg: [{
        url: file.url,
        size: file.size
      }]
    })
    wx.showLoading({
      title: '正在上传正脸参考图...',
    })
    // 这里添加实际的上传服务器逻辑
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      success: (res)=> {
        wx.hideLoading()
        let resData = JSON.parse(res.data);
        if (resData.result == 1) {
          this.setData({
            refer_img: resData.data.img_url
          })
        } else {
          this.setData({
            bodyReferImg: []
          })
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },fail(){
        wx.hideLoading()
      }
    })
  },

  // 删除文件
  onDeleteReferImg() {
    this.setData({ bodyReferImg: [] })
  },
  async submitUploadReferImg() {
    if (!this.data.bodyReferImg.length) {
      app.tips('请先上传正脸参考图');
      return;
    }
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.body-clone.upload-refer-img');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.data.business_id || 0,
        refer_img: this.data.refer_img,
        id: this.data.lip_duration_unused_body.id
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    app.tips('编辑正脸参考图'+msg);
    if (!result) return;
    this.setData({
      ['lip_duration_unused_body.refer_img']: data.img_url,
      showDigital: false,
      showDialog: this.data.lip_duration_unused_video_id?true: false
    })
  },

  async submitLip(){
    let _form = {
      video_id: this.data.lip_duration_unused_video_id
    }
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.video.lip-match');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.data.business_id || 0,
        form: _form
      }
    });
    let {
      result,
      msg,
      data
    } = response.data;
    wx.showModal({
      title: '提示',
      content: '提交匹配' + msg,
      success (res) {}
    })
    this.init();
    this.setData({
      lip_duration_unused_video_id: null,
      showDialogUnReferImg: false
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    if( this.data.timer) {
      clearInterval(this.data.timer);
      this.data.timer = null;
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.init();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getTabsList();//加载更多
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      path: '/mircoApp/ai-create/SpacePortal/index',
    };
  }
})